<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017\10\23 0023
 * Time: 15:26
 */
namespace app\home\controller;
use think\Controller;
use think\Db;
use think\Request;
use think\Cache;
use think\Session;
use think\response\Json;
class Users extends Controller
{

    /*
     * 用户登录
     *
     * */
    public function login()
    {

        if (Request::instance()->post()) {
            $param = Request::instance()->post();

            $mobile = $param['mobile'];
            $user_pwd = $param['user_pwd'];
            $data['user_lasttime'] = time();


            $where = ['mobile' => $mobile];

            $res = Db::table('users')->where($where)->find();

            if ($res) {
                if (md5(md5($user_pwd) . $res['user_no']) == $res['user_pwd']) {

//                        Db::table('users')->where($where)->insert($data);

                    Session::set('USERS', $res);

                    echo json_encode(0);
                    exit;

                } else {
                    echo json_encode(1);
                    exit;
                }
            } else {
                echo json_encode(2);
                exit;
            }
        }

        return $this->fetch();

    }

    /*
     * 用户注册
     *
     * */
    public function register()
    {
        return $this->fetch();
    }

    /**
     * 用户注册处理
     */
    public function addUser()
    {

        $user_model = new \app\home\model\Users();
        $register = $user_model->add_user_info();

        echo json_encode($register);
    }

    /**
     * 发送手机验证码
     */
    public function send_sms_code()
    {
        header('Content-Type: text/plain; charset=utf-8');
        $param = Request::instance()->post();
        $mobile = $param['mobile'];
        $accessKeyId = "LTAIz4qwld4JhGBD";
        $accessKeySecret = "W5GI4y9px8VQrvzc2NiJaOn0E7bPAt";
        $signName = "创学习";
        $templateCode = "SMS_94605099";
        $phoneNumbers = $mobile;
        $send_class = new \SmsDemo($accessKeyId, $accessKeySecret);
        $code = _rand_str(4);
        Cache::set('mobile_code', $code);
        $send_code = $send_class->sendSms(
            $signName,
            $templateCode,
            $phoneNumbers,
            ['number' => $code]
        );
        $send_data = json_encode($send_code);
        $obj = json_decode($send_data);
        if ($obj->{'Code'} === 'OK') {
            return json(['code' => 1, 'msg' => '发送成功！']);
        } else {
            return json(['code' => -1, 'msg' => $obj->{'Message'}]);
        }
    }

    /*
     * 忘记密码
     *
     * */
    public function forget()
    {
        return $this->fetch();
    }


    //处理忘记密码
    public function toForget(){

        $param=Request::instance()->post();
        $mobile=$param['mobile'];
        $user_pwd=$param['user_pwd'];
        $sms_code=$param['verify_code'];

        if(empty($mobile) || empty($user_pwd) || empty($sms_code)){
            echo 1;
            exit;

//                      $this->error("请填写完整信息!",url('home/users/forget'));
        }

        if ($sms_code != Cache::get('mobile_code')) {
            echo 2;
            exit;
//                     $this->error("验证码错误！", url("home/users/forget"));
        }

        $where=['mobile'=>$mobile];

        $res=Db::table('users')->where($where)->find();


        if($res['mobile']!=$mobile){
            echo 3;
            exit;

//                     $this->error("用户不存在或者账号错误!",url('home/users/forget'));
        }

        $rand_str = _rand_str(4);

        $user_model = new \app\home\model\Users();

        $register = $user_model->for_get_pwd($user_pwd,$mobile,$rand_str);

        if($register!==false){
            echo 0;
            exit;
//                        $this->success("修改成功！",url('home/users/login'));
        }else{
            echo 4;
            exit;
//                        $this->error("修改失败！",url('home/users/forget'));
        }
    }

    //退出
    public function login_out(){

          Session::clear();

          echo json_encode(1);
          exit;
          
    }

    //升级会员
    public function upVip(){
        $row = Session::get("USERS");
        $id = $row['user_id'];
        $this->view->assign('id',$id);
        return view();
    }

    public function toVip(){
        $row = Session::get("USERS");
        $id = $row['user_id'];
        $this->view->assign('id',$id);
        return view();
    }

    public function toVips(){
        $re = Request::instance()->post();
        $id = $re['id'];
        if(empty($re['yi'])){
            $this->redirect('home/index/index');
        }

        $yi = $re['yi'];
        $m = Db::table("users")->where("user_id = $id")->find();
        $integral = $m['user_integral'];
        $row = $this->setVips($id,$yi,$integral);
        if($row ==1){
            return view("isok");
        }elseif ($row == 2){
            return view("isno");
        }

    }

    //升级高级会员
    public function upVips(){
        $re = Request::instance()->post();
        $id = $re['id'];
        if(empty($re['yi'])){
            $this->redirect('home/index/index');
        }

        $yi = $re['yi'];
        $m = Db::table("users")->where("user_id = $id")->find();
        $integral = $m['user_integral'];
        $row = $this->setVip($id,$yi,$integral);
        if($row ==1){
            return view("isok");
        }elseif ($row == 2){
            return view("isno");
        }

    }

    public function setVip($id, $time,$integral)
    {
        $int = $integral + 100;
        $deta = [
            "user_id" => "$id",
            "score" => 100,
            "data_src"=> 2,
            "data_id"=>95000,
            "score_type"=> 1,
            "data_remarks"=> "会员开通赠送",
            "score_time" => time()
        ];
        Db::table('score')->insert($deta);


        if ($time == 1) {
            $data = [
                'uid' => "$id",
                'time' => time(),
                'endtime' => strtotime('+1 month')
            ];
        } elseif ($time == 2) {
            $data = [
                'uid' => "$id",
                'time' => time(),
                'endtime' => strtotime('+2 month')
            ];
        } elseif ($time == 3){
            $data = [
                'uid' => "$id",
                'time' => time(),
                'endtime' => strtotime('+3 month')
            ];

        }
        $row = Db::table("time")->insert($data);
        if($row>0){
            $jg = Db::table('users')->where('user_id',$id)->update(['user_grade' => 1,"user_integral"=> $int]);
            $user = Db::table('users')->where('user_id',$id)->find();
            Session::set("USERS",$user);
        }
        if($jg>0){
            return 1;
        }else{
            return 2;
        }
    }

    public function setVips($id, $time,$integral)
    {
        $int = $integral + 200;
        $deta = [
          "user_id" => "$id",
            "score" => 200,
            "data_src"=> 2,
            "data_id"=>95000,
            "score_type"=> 1,
            "data_remarks"=> "高级会员开通赠送",
            "score_time" => time()
        ];
        Db::table('score')->insert($deta);

        if ($time == 1) {
            $data = [
                'uid' => "$id",
                'time' => time(),
                'endtime' => strtotime('+1 month')
            ];
        } elseif ($time == 2) {
            $data = [
                'uid' => "$id",
                'time' => time(),
                'endtime' => strtotime('+2 month')
            ];
        } elseif ($time == 3){
            $data = [
                'uid' => "$id",
                'time' => time(),
                'endtime' => strtotime('+3 month')
            ];

        }
        $row = Db::table("time")->insert($data);
        if($row>0){
            $jg = Db::table('users')->where('user_id',$id)->update(['user_grade' => 2,"user_integral"=> $int]);
            $user = Db::table('users')->where('user_id',$id)->find();
            Session::set("USERS",$user);
        }
        if($jg>0){
            return 1;
        }else{
            return 2;
        }
    }

    
}